# -*- coding: utf-8 -*-
"""
Created on Mon Sep 28 13:32:23 2020

@author: Robin
"""
import re
import pandas as pd
import datetime
from lib.IOFile import *
from WindPy import *
w.start()

# In[0]： 保存数据
#savepath = 'data'
savepath = ''
begdate = datetime.datetime(2007,1,15)      # 中证500上市日期
enddate = datetime.datetime.now()
index_code = '000905.SH'

# 每个月第一天提取上个月的成分及权重信息
datelist = []
for year in range(begdate.year,enddate.year+1):
    for month in range(12):
        datetmp = datetime.datetime(year,month+1,1).strftime('%Y%m%d')
        datelist.append(datetmp)
for month in range(12-enddate.month):
    datelist.pop()
datelist.reverse()
for month in range(begdate.month):
    datelist.pop()
datelist.reverse()

# 信息提取
index_components = pd.DataFrame()
for datetmp in datelist:
    errorid,datatmp = w.wset("indexconstituent","date="+datetmp+";windcode="+index_code,usedf = True)
    if errorid != 0:
        print(errorid)
        print(datetmp)
        break
    else:
        index_components = pd.concat([index_components,datatmp])
        
index_components = index_components.rename(columns = {'wind_code':'asset'})
# .set_index(pd.MultiIndex.from_frame(index_components[['date','asset']]))
# 保存数据        
saveData(index_components,'index_components_'+re.sub('[.]','',index_code),savepath)

# In[1]：处理数据
# index_components = readjson('index_components_'+re.sub('[.]','',index_code),savepath)
